<?php

namespace support;

use app\services\ConfigService;
use Overtrue\Socialite\SocialiteManager;
use plugin\admin\app\model\Auth;

class Socialite
{
    public static function getInstance($type)
    {
        $auth = Auth::where('key', $type)->first();

        if (!$auth) {
            throw new \Exception('不支持的登录方式');
        }

        if (!$auth['is_enable']) {
            throw new \Exception('当前登录方式已被禁用');
        }

        $config = ConfigService::getByGroup($type . '_auth');

        if (!$config) {
            throw new \Exception('不支持的授权方式');
        }

        foreach ($config as $value) {
            if (empty($value)) {
                throw new \Exception('当前授权方式为' . $type . ', 配置未完善, 请在后台->授权处完善配置信息');
            }
        }

        switch ($type) {
            default:
            case 'wechat':
                $innerConfig = [
                    'client_id' => $config['wechat_auth_client_id'],
                    'client_secret' => $config['wechat_auth_client_secret'],
                    'redirect' => $config['wechat_auth_redirect_url']
                ];
                break;
            case 'alipay':
                $innerConfig = [
                    'client_id' => $config['alipay_auth_client_id'],
                    'rsa_private_key' => $config['alipay_auth_rsa_private_key'],
                    'redirect' => $config['alipay_auth_redirect_url'],
                    'sandbox' => boolval($config['alipay_auth_sandbox'])
                ];
                break;
            case 'qq':
                $innerConfig = [
                    'client_id' => $config['qq_auth_client_id'],
                    'client_secret' => $config['qq_auth_rsa_private_key'],
                    'redirect' => $config['qq_auth_redirect_url'],
                ];
                break;
        }

        $socialiteConfig = [
            $type => $innerConfig
        ];

        $socialite = new SocialiteManager($socialiteConfig);
        return $socialite->create($type);
    }

    public static function getOpenField($type)
    {
        switch ($type) {
            case 'wechat':
                return 'wechat_open_id';
            case 'qq':
                return 'qq_open_id';
            case 'alipay':
                return 'alipay_open_id';
        }
    }
}